package org.ttjhome.html.struts.job;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ttjhome.db.dbo.Activity;
import org.ttjhome.db.dbo.ActivityRecord;
import org.ttjhome.db.dbo.Job;
import org.ttjhome.db.dbo.Tag;
import org.ttjhome.db.dbo.User;
import org.ttjhome.html.struts.ActionMessageRegistry;
import org.ttjhome.html.struts.candidate.Constants;
import org.ttjhome.html.struts.common.SecurityConstants;
import org.ttjhome.html.struts.util.TagsCache;
import org.ttjhome.server.HunterServiceFactory;
import org.ttjhome.util.StringUtils;

public class JobsAction extends DispatchAction{

	private static final Logger logger = Logger.getLogger(JobsAction.class
			.getName());
	
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return list(mapping, form, request, response);
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering execute of JobsAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		
		DynaActionForm queryForm = (DynaActionForm) form;
		ActionMessages actionMessages = new ActionMessages();
		if (!actionMessages.isEmpty())
		{
			actionMessages.add("pageerror",  new ActionMessage( "ERR_PROBLEM_IN_INPUT" ));
			request.setAttribute("ACTION_MESSAGES", actionMessages);
			return mapping.findForward("success");
		}
		  
	
		initQueryForm(request, queryForm);
		
		return actionForward;
	}


	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	
		logger.info("Entering edit of JobsAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		DynaActionForm editForm = (DynaActionForm) form;
		User user = SecurityConstants.gSessionAccount.get(request);
		ActionMessages actionMessages = new ActionMessages();
		String filter = (String) editForm.get(Constants.KEY_FILTER); 
		String jobID=(String)editForm.get(Constants.INPUT_JOB_ID);
		 
		if (StringUtils.isEmpty(jobID))
		{
			logger.info("The jobID is missing, redirect to company list page!");
			return mapping.findForward(Constants.FORWARD_LIST);
		}
		
		Job job = HunterServiceFactory.createHunterService().getJob(Long.valueOf(jobID));
		
		if (!StringUtils.isEmpty(filter))
		{
			if (!isTokenValid(request, true))
			{
				resetToken(request);
				return mapping.findForward(Constants.FORWARD_LIST);
			}
			if(Constants.JOB_CLOSED_STATUS.equalsIgnoreCase(job.getStatus()))
			{
				actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.JOB_STATUS_CLOSED);
				actionMessages.add(Constants.INPUT_JOB_STATUS, ActionMessageRegistry.JOB_STATUS_CLOSED);
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			verifyJobForm(actionMessages,editForm);
			if (!actionMessages.isEmpty())
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			copyFormValueToJob(request,job, editForm,user);
			try
			{
				job = HunterServiceFactory.createHunterService().saveJob(job);
			}catch(Exception e)
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			logger.info("Updated Job "+job.getName() +" successfully ");
			request.setAttribute(Constants.ATTR_SUCCESS_MESSAGE_TYPE, Constants.ATTR_SUCCESS_MESSAGE_TYPE_SAVING);
			request.setAttribute(Constants.ATTR_SUCCESS_JOB,job);
			actionForward = mapping.findForward("success");
			editForm.set(Constants.KEY_FILTER, "");
		}else
		{	
			saveToken(request);
			editForm.set(Constants.KEY_FILTER, Constants.KEY_FILTER_EDIT);	
			copyJobToForm(job, editForm, request);
		
		}
		if(job.getTags()!=null&&job.getTags().size()>0)
		{
			List<Tag> tags = new ArrayList<Tag>();
			tags.addAll(job.getTags());
			request.setAttribute(Constants.INPUT_CANDIDATE_TAGS, tags.toArray());
		}
		return actionForward;
	}
	 

	
	private void copyJobToForm(Job job,
			DynaActionForm editForm, HttpServletRequest request) {
	
		editForm.set(Constants.INPUT_JOB_NAME, job.getName());
		editForm.set(Constants.INPUT_COMPANY_DESCRIPTION, job.getDescription());
		editForm.set(Constants.INPUT_JOB_STATUS, job.getStatus());
	}

	private void copyFormValueToJob(HttpServletRequest request, Job job,
			DynaActionForm form, User user) {
		String jobName = form.getString(Constants.INPUT_JOB_NAME);
		String description = form.getString(Constants.INPUT_COMPANY_DESCRIPTION);
		String[]  tags = form.getStrings(Constants.INPUT_CANDIDATE_TAGS);
		job.setName(jobName);
		job.setDescription(description);
		
		//tags
		//clear first 
		job.getTags().clear();
		for(int i=0;i<tags.length;i++)
		{
			Tag tag = TagsCache.getTag(tags[i]);
			if(tag==null)
			{
				//add a new one 
				logger.info("Save new Tag "+tags[i]);
				tag = HunterServiceFactory.createHunterService().saveTag(tags[i]);
			}
			
			job.getTags().add(tag);
		}
		
	}

	
	
	

	private void verifyJobForm(ActionMessages actionMessages,
			DynaActionForm createForm) {
		String jobName = createForm.getString(Constants.INPUT_JOB_NAME);
		if(StringUtils.isEmpty(jobName))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.JOB_NAME_INVALID);
			actionMessages.add(Constants.INPUT_JOB_NAME, ActionMessageRegistry.JOB_NAME_INVALID);
		}
		
		
		
	}

	
	public ActionForward listActivities(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering listActivities of CandidatesAction");
		String jobId = request.getParameter("jobId");
		logger.info("listActivities jobId"+jobId);
		Job job = HunterServiceFactory.createHunterService().getJob(Long.valueOf(jobId));
		if(job==null){
			logger.info(" job not found");
			return null;
		}
		List<Activity> activities = HunterServiceFactory.createHunterService().getActivities(job);
		JSONObject json =translateActivitiesToJson(activities);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());

		return null;
	} 
	
	private JSONObject translateActivitiesToJson(Collection<Activity> activities) throws Exception{
		
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray();
		
		for(Activity activity:activities){
			JSONObject tmp = new JSONObject();
			JSONArray records = new JSONArray();
			List<ActivityRecord> activityRecords = new ArrayList<ActivityRecord>();
			activityRecords.addAll(activity.getRecords());
			Collections.sort(activityRecords,new ActivityRecordComparator());
			for(ActivityRecord record :activityRecords){
				JSONObject recordJSON = new JSONObject();
				if(record.getRecordTime()!=null)
					recordJSON.put("recordTime", record.getRecordTime().toString());
				else
					recordJSON.put("recordTime", "Unknown time");
				if(record.getActivityTime()!=null)
					recordJSON.put("activityTime", record.getActivityTime().toString());
				recordJSON.put("record", record.getRecord());
				records.put(recordJSON);
			}
			tmp.put("id", activity.getId());
			tmp.put("status",activity.getStatus());
			tmp.put("candidateName", activity.getCandidate().getName());
			tmp.put("candidateId", activity.getCandidate().getId());
			tmp.put("records", records);

			array.put(tmp);
		}
		json.put("result", 0);
		json.put("data", array);
		return json;
	}
	

	public static void initQueryForm(HttpServletRequest request, DynaActionForm queryForm) {
		
	}
	
	public class ActivityRecordComparator implements Comparator<ActivityRecord> {

		 public int compare(ActivityRecord o1, ActivityRecord o2) {
			 if(o1.getActivityTime()!=null&&o2.getActivityTime()!=null){
				 return o1.getActivityTime().compareTo(o2.getActivityTime());
			 }
			 return o1.getRecordTime().compareTo(o2.getRecordTime());
		 }
		}
}
